package com.qk.management.web.interceptor;

import com.qk.common.util.jwt.JwtUtils;
import com.qk.common.util.thread.CurrentLoggedInUserIDData;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-10-11 15:48
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN_HEADER_NAME);
        Optional<String> tokenOptional = Optional.ofNullable(token);
        if(tokenOptional.isEmpty()){
            log.info("请求头中没有token");
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJwts(token);
            log.info("token验证成功");
            CurrentLoggedInUserIDData.set((Integer)claims.get(JwtUtils.CLAIMS_KEY_TWO));
            return true;
        }catch (Exception e) {
            log.info("token验证失败:{}",e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentLoggedInUserIDData.remove();
    }
}
